﻿using UnityEngine;
public static class RectTransformExtensions
{
    public static Vector2 GetScreenPosition(this RectTransform rectTransform, Camera uiCamera)
    {
        Vector2 screenPosition = RectTransformUtility.WorldToScreenPoint(uiCamera, rectTransform.position);
        return screenPosition;
    }

    public static Vector2 GetWorldPosition(this RectTransform rectTransform, Camera worldCamera)
    {
        return worldCamera.ScreenToWorldPoint(rectTransform.position);
    }


    /// <summary>
    /// 获取RectTrasnform在World的rect
    /// 
    /// </summary>
    /// <param name="rectTransform"></param>
    /// <param name="worldCamera"></param>
    /// <returns></returns>
    public static Rect GetWorldRect(this RectTransform rectTransform, Camera worldCamera)
    {
        Vector3[] corners = new Vector3[4];
        rectTransform.GetWorldCorners(corners);

        Vector2 min = worldCamera.ScreenToWorldPoint(corners[0]);
        Vector2 max = worldCamera.ScreenToWorldPoint(corners[2]);

        return new Rect(min, max - min);
    }

    public static void SetWorldPosition(this RectTransform rectTransform, Vector3 worldPosition, Camera worldCamera)
    {
        rectTransform.position = worldCamera.WorldToScreenPoint(worldPosition);
    }

    public static Vector2 GetRandomPos(this RectTransform rectTransform)
    {
        Rect rect = rectTransform.rect;

        // 在矩形区域内随机生成一个点
        float randomX = Random.Range(rect.xMin, rect.xMax);
        float randomY = Random.Range(rect.yMin, rect.yMax);

        // 将局部坐标转换为世界坐标
        Vector2 localPoint = new Vector2(randomX, randomY);
        Vector2 worldPoint = rectTransform.TransformPoint(localPoint);

        return worldPoint;
    }

}
